package cn.tyf.controller;

import cn.tyf.common.ConstAutoConfig;
import cn.tyf.domain.PageBean;
import cn.tyf.domain.Record;
import cn.tyf.domain.ResultInfo;
import cn.tyf.domain.User;
import cn.tyf.service.RecordService;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/record")
public class RecordController {

    @Autowired
    @Qualifier("resultInfo")
    private ResultInfo info;

    @Autowired
    private RecordService recordService;

    @Autowired
    private ConstAutoConfig constAutoConfig;

    @RequestMapping("/findRecord")
    @ResponseBody
    public ResultInfo findRecord(String names,Integer currentPage,Integer pageSize) {
        PageBean byPage = recordService.findByPage(names,currentPage, pageSize);
        if (byPage != null) {
            info.setFlag(true);
            info.setData(byPage);
        }
        return info;
    }

    /**
     * 用户访问记录分页查询
     * @param rid
     * @param current
     * @param pageSize
     * @return
     */
    @RequestMapping("/findPageByUser")
    @ResponseBody
    PageBean<Record> findPageByUser(String rid, String time, Integer current, Integer pageSize){
        return  recordService.findPageByUser(rid, time,current, pageSize);
    }

    @RequestMapping("/addAnnal")
    @ResponseBody
    public void addAnnal(String card, String time, Integer door){
        recordService.addAnnal(card,time,door);
    }

    @RequestMapping("/downloadRecord")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        List<Record> recordList = recordService.findAll();
        String fileName = URLEncoder.encode("访问记录表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Record.class).sheet("访问记录").doWrite(recordList);
    }
}
